import com.rabbitmq.client.Channel
import com.rabbitmq.client.Connection
import com.rabbitmq.client.ConnectionFactory
import com.rabbitmq.client.QueueingConsumer

/**
 * Testing rabbitmq with Producer and Consumer
 * @author: linyu
 * @version: 3/22/16
 */

def Sending() {
    String uri = (args.length > 0) ? args[0] : "amqp://localhost";
    String message = (args.length > 1) ? args[1] :
            "the time is " + new java.util.Date().toString();
    String exchange = (args.length > 2) ? args[2] : "";
    String routingKey = (args.length > 3) ? args[3] : "SimpleQueue";

    ConnectionFactory cfconn = new ConnectionFactory();
    cfconn.setUri(uri);
    Connection conn = cfconn.newConnection();

    Channel ch = conn.createChannel();

    if (exchange.equals("")) {
        ch.queueDeclare(routingKey, false, false, false, null);
    }

    for(int i=0;i<100;i++) {
        ch.basicPublish(exchange, routingKey, null, message.getBytes());
    }

    ch.close();
    conn.close();
}

def Recieving() {
    String uri = (args.length > 0) ? args[0] : "amqp://localhost";
    String queueName = (args.length > 1) ? args[1] : "SimpleQueue";

    ConnectionFactory connFactory = new ConnectionFactory();
    connFactory.setUri(uri);
    Connection conn = connFactory.newConnection();

    final Channel ch = conn.createChannel();

    ch.queueDeclare(queueName, false, false, false, null);

    QueueingConsumer consumer = new QueueingConsumer(ch);
    ch.basicConsume(queueName, consumer);
    while (true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        System.out.println("Message: " + new String(delivery.getBody()));
        ch.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
    }
}

Sending()
Recieving()
